import { _decorator, Animation, AnimationClip, AudioClip, Component, find, Label, Node, resources, Sprite, sys, UITransform, Vec2, Vec3 } from 'cc';
import { GLOBALUtil } from './GlobalUtil';
import { GLOBALVar } from './GlobalVar';
import { WebSocketManager } from './WebSocketManager';
import { GLOBALPOP } from './GlobalPop';
import { SoundManager } from './SoundManager';
import { NoticeManager } from './NoticeManager';
const { ccclass, property } = _decorator;

type Notice = {
    msg: string,
    id: number,
    content: string
}
type UserData = {
    nickname: string,
    avatar_url: string
}
@ccclass('MenuSceneManager')
export class MenuSceneManager extends Component {
    @property({type: Node})
    private Avatar: Node | null = null;
    @property({type: Node})
    private Nickname: Node | null = null;
    @property({type: Node})
    private NameBG: Node | null = null;
    @property({type: Node})
    private NodeMenu: Node | null = null;
    @property({type: Node})
    private PersonalPage: Node | null = null;
    @property({type: Node, tooltip: "公告面板"})
    private NoticeNode: Node | null = null;

    protected onEnable(): void {
        this.updateUI();
    }
    async start() {
        //获取当前使用的卡牌皮肤
        GLOBALVar.CardFrameUsed = await GLOBALUtil.getCardFrameUsed();
        //加载公告
        const response: Notice = await GLOBALUtil.getNotice() as Notice;
        if (response.msg === "暂无公告") {
            //不显示内容，啥也不做
        } else {
            //读取本地的公告是否显示数据
            const key = `isHideNotice_${response.id}`;
            const flag = localStorage.getItem(key);
            if ((flag === "0" || flag === null) && !GLOBALVar.noticeState) {
                //显示公告或者当flag === null 显示新的公告(也有可能是用户没有勾选过)
                this.NoticeNode.active = true;
                GLOBALVar.noticeState = true;
            }
        }
        // 确保 SoundManager 提前初始化
        SoundManager.getInstance();

        // 延迟加载音频确保节点创建完成
        this.scheduleOnce(() => {
            resources.load('Audios/dgqgdyz_funk', AudioClip, (err, clip) => {
                if (err) {
                    console.error(err);
                    return;
                }
                const soundManager = SoundManager.getInstance();
                soundManager.playBGM(clip, 0.7);
            });
        }, 0);

        //Android平台不知道是不是SSL认证的问题还是什么导致无法正常建立webSocket连接，因此webSocket只考虑在web平台使用
        if (sys.isBrowser) {

            //成功登陆后，建立websocket连接
            const wsManager = WebSocketManager.getInstance();

            const handleMessage = (data: string) => {
                const jsonData = JSON.parse(data);
                // 在这里进行消息处理，例如解析JSON数据
                try {
                    if (jsonData.type === "token_verify") {
                        if (jsonData.status === "success") {
                            console.log("Token验证成功");
                        } else {
                            wsManager.close("FirstConnect");
                            console.log("Token验证失败");
                            GLOBALUtil.LoadMessage(true, "Token验证失败, 尝试重新登录！", this.node, new Vec3(50, 950, 0), true, 2)
                        }
                    }
                } catch (error) {
                    console.error('Error parsing JSON:', error);
                }
            };


            wsManager.connect("FirstConnect", GLOBALVar.WEBSOCKET_ADDRESS);
            //注册事件监听器
            wsManager.on("FirstConnect", handleMessage);
    
            //首次连接验证token
            const data = {
                type: "token_verify",
                token: localStorage.getItem("token"),
            }
            setTimeout(() => {
                wsManager.send("FirstConnect", JSON.stringify(data));
            }, 500);
        }
    }

    update(deltaTime: number) {
        
    }

    public async updateUI() {
        //获取用户头像以及Nickname
        try {
            if (GLOBALVar.avatarUrlCache == null || GLOBALVar.nicknameCache == null) {
                const userData = await GLOBALUtil.getUserInfo() as UserData;
                GLOBALVar.avatarUrlCache = userData.avatar_url;
                GLOBALVar.nicknameCache = userData.nickname;
            }
            
            this.Nickname.getComponent(Label).string = GLOBALVar.nicknameCache;
            //开一个Schedule, 下一帧再获取用户名宽度调整背景框，防止异步问题。
            this.scheduleOnce(() => {
                this.NameBG.getComponent(UITransform).width = this.Nickname.getComponent(UITransform).width + 100;
            }, 0);
            const AvatarSp = this.Avatar.getComponent(Sprite);
            if (GLOBALVar.avatarSpriteCache == null) {
                GLOBALUtil.loadNetImage(GLOBALVar.avatarUrlCache, (Sp) => {
                    GLOBALVar.avatarSpriteCache = Sp;
                    AvatarSp.spriteFrame = GLOBALVar.avatarSpriteCache;
                })
            } else {
                AvatarSp.spriteFrame = GLOBALVar.avatarSpriteCache;
            }

        } catch (error) {
            console.error(error);
        }
    }

    onClickClose() {
        const Anime = this.NodeMenu.getChildByName("AnimeNode").getComponent(Animation);
        const AnimeClip = Anime.clips[0];
        AnimeClip.wrapMode = AnimationClip.WrapMode.Reverse;    //Anime是引用的数据，因此不会对原数据造成影响
        Anime.clips = [AnimeClip];
        Anime.play();
        Anime.once(Animation.EventType.FINISHED, () => {
            this.NodeMenu.active = false;
        })
    }

    //点击头像打开个人资料
    onClickAvatar() {
        this.PersonalPage.active = true;
    }
    onClickBtnMenu() {
        this.NodeMenu.active = true;
        const Anime = this.NodeMenu.getChildByName("AnimeNode").getComponent(Animation);
        const AnimeClip = Anime.clips[0];
        AnimeClip.wrapMode = AnimationClip.WrapMode.Normal;
        Anime.clips = [AnimeClip];
        Anime.play();
    }    
}